from common.utils import empty, init_item
from db.db_connection_pool import get_connection


def query(query_arr):
    results = []
    # 暂时写死
    if len(query_arr) < 3:
        return results
    # 只打包前三个数据
    table_name, field, value = query_arr[0:3]
    value = 0 if empty(value) else value
    sql = "SELECT * FROM %s WHERE %s = '%s'" % (table_name, field, value)
    db_connection = get_connection()
    cursor = db_connection.cursor()
    cursor.execute(sql)
    data = cursor.fetchall()
    if empty(data):
        return results
    field_filter = []
    if len(query_arr) > 4:
        field_filter = query_arr[3:]
    if len(data) == 1:
        # 只有一个数据的时候展示所有的数据
        return init_single_data(data[0], field_filter)
        pass
    for single_data in data:
        results.append(pack_data(single_data, field_filter))
        pass
    return results
    pass


def init_single_data(data, field_filter):
    rs = []
    for field in data:
        if empty(field_filter) or field in field_filter:
            show_str = "%s => %s" % (field, data[field])
            rs.append(init_item(text=show_str, subtext=show_str))
    return rs
    pass


def pack_data(data, field_filter):
    whole_value = ''
    if empty(field_filter):
        for field in data:
            if isinstance(data[field], str) and len(data[field]) > 20:
                continue
            whole_value += "%s:%s, " % (field, data[field])
    return init_item(text=whole_value)
    pass
